package test;

public class DoubleLinkedList {
    //双向链表------------------
    //头节点
    Node headNode;
    //尾节点
    Node lastNode;
    //有效节点个数
    int size;

//--------增
    public void add(Object key){
        //双向链表为空未存储数据
        if(size==0&&headNode==null){
            Node node=new  Node(key,null,null);
            headNode=node;
            size++;
            return;
        }
        if(size==1&&headNode!=null){
            Node node=new  Node(key,headNode,null);
            headNode.next=node;
            lastNode=node;
            size++;
            return;
        }
        Node node=new  Node(key,lastNode,null);
        lastNode.next=node;
        lastNode=node;
        size++;
    }
//--------删
    public void remove(Object key){
        if(headNode==null){
            throw new RuntimeException("无法删除空链表节点");
        }
        //被删除的节点
        Node node=headNode;

        while(size>=3){
            if(node.key==key){
            node.front.next=node.next;
            node.next.front=node.front;
            size--;
            return;
        }
            node=node.next;
        }
            if(size==1){
            if(key==headNode.key){
                headNode=null;
                size--;
                return;
            }
        }
            if(size==2){
                if(key==headNode.key){

                    lastNode.front=null;
                    headNode=lastNode;
                    lastNode=null;
                    size--;
                    return;
                }
                if(key==lastNode.key){
                    lastNode=null;
                    headNode.next=null;
                    size--;
                    return;
                }
            }
    }
//--------查
    public void allQuery(){
        if(size==0){return;}
        Node node = headNode;
        while (true){
            System.out.println(node.key);

            if(node.next==null){
                break;
            }
            node=node.next;
        }
    }

    //节点内部类
    public class Node{
        //存储的元素
        Object key;
        //上一个节点
        Node front;
        //下一个节点
        Node next;

        public Node(Object key, Node front, Node next) {
            this.key = key;
            this.front = front;
            this.next = next;
        }



    }
}
